﻿@* 应用层Web Api项目启动配置 *@
@using Util.Generators.Helpers
@model Util.Generators.Contexts.EntityContext
@{
    var service = new GenerateService( Model );
    Model.Output.FileNameNoExtension = "Startup";
    Model.Output.Extension = ".cs";
    Model.Output.RelativeRootPath = $"test/{service.GetWebApiTestProjectName()}";
}
using Util;
using Util.Helpers;
using @service.GetDataNamespace();
using @service.GetDataNamespace( Model.ProjectContext.TargetDbType );

namespace @service.GetWebApiTestNamespace() {
    /// <summary>
    /// 启动配置
    /// </summary>
    public class Startup {
        /// <summary>
        /// 配置主机
        /// </summary>
        public void ConfigureHost( IHostBuilder hostBuilder ) {
            Util.Helpers.Environment.SetDevelopment();
            hostBuilder.ConfigureDefaults( null )
                .ConfigureWebHostDefaults( webHostBuilder => {
                    webHostBuilder.UseTestServer()
                    .Configure( t => {
                        t.UseRouting();
                        t.UseEndpoints( endpoints => {
                            endpoints.MapControllers();
                        } );
                    } );
                } )
                .AsBuild()
                .AddAop()
                @if ( service.Utc() ) {
                @:.AddUtc()
                }
                .@service.AddUnitOfWork()<@service.GetIUnitOfWork(),@service.GetUnitOfWork()>( Config.GetConnectionString( "TestConnection" ) )
                .AddUtil();
        }

        /// <summary>
        /// 配置服务
        /// </summary>
        public void ConfigureServices( IServiceCollection services ) {
            services.AddLogging( logBuilder => logBuilder.AddXunitOutput() );
            services.AddControllers();
            services.AddTransient<IHttpClient>( t => {
                var client = new HttpClientService();
                client.SetHttpClient( t.GetService<IHost>().GetTestClient() );
                return client;
            } );
            InitDatabase( services );
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        private void InitDatabase( IServiceCollection services ) {
            var unitOfWork = services.BuildServiceProvider().GetService<@service.GetIUnitOfWork()>();
            unitOfWork.EnsureDeleted();
            unitOfWork.EnsureCreated();
        }
    }
}